$(function () {
  $("#loginBox a").on("click", function () {
    $("#registerBox").show();
    $("#loginBox").hide();
  });
  $("#registerBox a").on("click", function () {
    $("#loginBox").show();
    $("#registerBox").hide();
  });

  // 自定义校验规则
  let form = layui.form;
  form.verify({
    pwd: [
      /^[\S]{6,12}$/,
      // 报错信息
      "密码长度为6-12个字符，且不包含空格",
    ],
    repwd: function (value) {
      let pwd = $("#registerBox [name=password]").val();
      if (value !== pwd) {
        return "输入的两次密码不一样！";
      }
    },
  });

  // 注册axios
  let layer = layui.layer;
  $("#form-reg").on("submit", function (e) {
    e.preventDefault();
    axios({
      method: "POST",
      url: "/api/reguser",
      data: $("#form-reg").serialize(),
    }).then(function (res) {
      // console.log(res.data);
      let obj = res.data;
      if (obj.status !== 0) {
        return layer.msg(obj.message);
      }
      layer.msg("恭喜您，注册成功！");
      $("#form-reg")[0].reset();
      $("#registerBox a").click();
    });
  });
  // 登录axios
  $("#form-login").on("submit", function (e) {
    e.preventDefault();
    axios({
      method: "POST",
      url: "/api/login",
      data: $("#form-login").serialize(),
    }).then(function (res) {
      let obj = res.data;
      if (obj.status !== 0) {
        return layer.msg(obj.message);
      }
      layer.msg("恭喜您，登录成功");
      location.href = "/index.html";
      localStorage.setItem("token", obj.token);
    });
  });
});
